<?php
/**
 * SpecialController class.
 * SpecialController is to handle all data about special table.
 * 
 * Yamii for Business 版权所有 @ 2010 - 2012.
 */
class SpecialController extends ApiController
{
	
	
	/**
	 * List valid specials the customer has.
	 * @param type $hid
	 * @param type $key
	 */
	public function actionList()
	{
		// set the page size
		$page_size = 10;
		
		// page=? or offset=?
		$page = (int)Yii::app()->request->getQuery('page', 0);
		$offset = (int)Yii::app()->request->getQuery('offset', 0);
		if ($page > 0) {
			$offset = ($page - 1) * $page_size;
		} else if ($offset > 0) {
			$page = floor($offset/$page_size) + 1;
		} else {
			$page = 1;
			$offset = 0;
		}
		$s_limit = " LIMIT {$offset}, " . $page_size;
		
		$params = array();
		
		// get distance if lat=? and lon=?
		$s_distance = 'NULL AS distance, ';
		$enable_geo = false;
		$latitude = Yii::app()->request->getQuery('lat', 0);
		$longitude= Yii::app()->request->getQuery('lon', 0);
		if ($latitude > 0 and $longitude > 0) {
			$enable_geo = true;
			$s_distance = '(6371 * acos(cos(radians(:lat)) * cos(radians(m.latitude)) * cos(radians(m.longitude) - radians(:lon)) + sin(radians(:lat)) * sin(radians(m.latitude)))) AS shop_distance ';
			$params[':lat'] = (float)$latitude;
			$params[':lon'] = (float)$longitude;
		}
		
		//2. fetch lunch special
		$sql_special = 'SELECT s.id, s.url_picture, s.content, s.show_hours, s.start_hour, s.end_hour, s.week_days,
			s.show_price, s.price, s.value, 100-(s.price/s.value * 100) AS discount, s.type, ' . $s_distance . '
			UNIX_TIMESTAMP(s.start_date) AS uts_start_date, UNIX_TIMESTAMP(s.end_date) AS uts_end_date,
			m.name, m.address, m.postcode, m.city, m.phone, m.url_logo, m.currency_code, m.category_key, m.latitude, m.longitude
			FROM tbl_merchant_special s
			INNER JOIN tbl_merchant_account m ON m.id = s.id_merchant
			WHERE s.status=1 AND s.start_date<NOW() AND s.end_date>NOW()
			ORDER BY s.published_time DESC, distance ASC'
			. $s_limit;
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_special);
		$special_rows = $command->queryAll(true, $params);
		$connection->active = false;
		
		$model = array();
		foreach ($special_rows as $r) {
			//set the valid period
			$validTime = BUtils::GetHourRangeFormat($r['start_hour'], $r['end_hour']);
			$validTime = empty($validTime) ? '24h' : $validTime;
			
			$model[] = array(
				'id' => $r['id'],
				'location' => $r['city'],
				'image' => empty($r['url_picture']) ? $r['url_logo'] : $r['url_picture'],
				'validDate' => BUtils::GetDateRangeString($r['uts_start_date'], $r['uts_end_date'], 'd.m'),
				'validTime' => $validTime,
				'value' => Yii::app()->locale->numberFormatter->formatCurrency($r['value'], $r['currency_code']),
				'price' => Yii::app()->locale->numberFormatter->formatCurrency($r['price'], $r['currency_code']),
				'discount' => $r['discount'],
				'category' => $r['category_key'],
				'description' => nl2br($r['content']),
				'lat' => $r['latitude'],
				'lon' => $r['longitude'],
				'distance' => empty($r['shop_distance']) ? 'null' : $r['shop_distance'],
				'vendor' => array(
					'name' => $r['name'],
					'address' => $r['address'] . ', ' . $r['postcode'] . ' ' . $r['city'],
					'phone' => $r['phone'],
				),
			);
		}
		$this->renderPartial('_list', array(
			'model' => $model,
			'count' => $page_size,
			'page' => $page,
			'offset' => $offset,
		));
	}
	
	/**
	 * Preview a special in HTML page.
	 *   hid=? and key=?
	 *   sid - special ID
	 *   code - Yamii code
	 * @param type $hid
	 * @param type $key 
	 */
	public function actionPreview() {
		$hid = Yii::app()->request->getParam('hid', null);
		$key = Yii::app()->request->getParam('key', null);
		$id = $this->_auth($hid, $key);
		
		$sid = Yii::app()->request->getParam('sid', null);
		$code = Yii::app()->request->getParam('code', null);
		if (empty($sid) and empty($code)) {
			$this->_sendError('The parameter "code" or "sid" is missing!');
		}
		
		$connection = Yii::app()->db;
		if (empty($sid)) {
			$sql_special = 'SELECT r.id_special, r.redeemed, r.redeemed_time
				FROM tbl_merchant_special_redeem r
				INNER JOIN tbl_merchant_special s ON r.id_special=s.id
				WHERE r.code=:code AND s.id_merchant=:id_merchant';
			$command = $connection->createCommand($sql_special);
			$row = $command->queryRow(true, array(
				'code' => $code,
				'id_merchant' => $id,
			));
			$sid = $row['id_special'];
		}
		$sql_special = 'SELECT s.id, s.url_picture, s.content, s.show_hours, s.start_hour, s.end_hour, s.week_days,
			s.show_price, s.price, s.value, 100-(s.price/s.value * 100) AS discount, s.type,
			UNIX_TIMESTAMP(s.start_date) AS uts_start_date, UNIX_TIMESTAMP(s.end_date) AS uts_end_date,
			m.name, m.address, m.postcode, m.city, m.phone, m.url_logo, m.currency_code
			FROM tbl_merchant_special s
			INNER JOIN tbl_merchant_account m ON m.id = s.id_merchant
			WHERE s.trash=0 AND s.id=:sid AND s.id_merchant=:id_merchant';
		$command = $connection->createCommand($sql_special);
		$row = $command->queryRow(true, array(
			'sid' => $sid,
			'id_merchant' => $id,
		));
		$connection->active = false;
		
		if (empty($row)) {
			$this->render('default');
		} else {
			$this->render('preview', array('row' => $row));
		}
	}
	
	/**
	 * Preview a instant special in HTML page.
	 *   hid=? and key=?
	 *   sid - special ID
	 *   code - Yamii code
	 * @param type $hid
	 * @param type $key 
	 */
	public function actionPreviewInstant() {
		$hid = Yii::app()->request->getParam('hid', null);
		$key = Yii::app()->request->getParam('key', null);
		$id = $this->_auth($hid, $key);
		
		//1. fetch merchants
		$sql_merchant = 'SELECT m.id, m.name, m.address, m.postcode, m.phone, m.city, m.country_code, m.currency_code,
			m.url_logo, m.url_site, m.latitude, m.longitude, m.opening, m.brief
			FROM tbl_merchant_account m
			WHERE id=:id ';
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_merchant);
		$row = $command->queryRow(true, array('id'=>$id));
		$connection->active = false;
		if (empty($row)) {
			$this->render('default');
		} else {
			$end_time = Yii::app()->request->getParam('end_time', mktime(date('H')+1, date('i')));
			$end_hour = date('H:i', $end_time);
			
			if (empty($row['url_logo'])) {
				$row['url_logo'] = 'http://yamii.fi/img/default_special_thumb.png';
			}
			
			$row['price'] = Yii::app()->request->getParam('new_price', null);
			$row['value'] = Yii::app()->request->getParam('old_price', null);
			$row['end_time'] = BUtils::T('end_time_at_lbl', array('{time_string}' => $end_hour));
			$row['type'] = Yii::app()->request->getParam('type');
			$row['content'] = Yii::app()->request->getParam('content');
			$this->render('previewInstant', array('row' => $row));
		}
	}
	
	/**
	 * Send a instant special.
	 *   hid=? and key=?
	 * @param type $hid
	 * @param type $key 
	 */
	public function actionSendInstant() {
		$hid = Yii::app()->request->getParam('hid', null);
		$key = Yii::app()->request->getParam('key', null);
		$id = $this->_auth($hid, $key);
		
		//auto-create for the start_time
		$start_time = time();
		$start_hour = date('Hi', $start_time);
		$start_time_full = date('Y-m-d H:i', $start_time);
		$start_week_no = date('N', $start_time);
		
		//check the end_time
		$end_time = Yii::app()->request->getParam('end_time', null);
		if (empty($end_time)) {
			$this->_sendError('The parameter end_time is missing!');
		}
		if (strlen($end_time) === 13) {
			$end_time = (int)($end_time / 1000);
		}
		$end_hour = date('Hi', $end_time);
		$end_time_full = date('Y-m-d H:i', $end_time);
		$end_week_no = date('N', $end_time);
		if ($start_week_no == $end_week_no) {
			$week_days = $start_week_no;
		} else {
			$week_days = $start_week_no . ',' . $end_week_no;
		}
		
		$row = array();
		$row['id_merchant'] = (int)$id;
		$row['price'] = Yii::app()->request->getParam('new_price', 0);
		$row['value'] = Yii::app()->request->getParam('old_price', null);
		if (empty($row['value'])) {
			$this->_sendError('The old_price is invalid!');
		}
		$row['start_hour'] = $start_hour;
		$row['end_hour'] = $end_hour;
		$row['week_days'] = $week_days;
		$row['start_date'] = $start_time_full;
		$row['end_date'] = $end_time_full;
		$row['max_number'] = Yii::app()->request->getParam('nop', 0);
		$row['content'] = Yii::app()->request->getParam('content');
		$row['discount'] = 1 - $row['price']/$row['value'];
		$row['status'] = 1;	// published status
		$row['type'] = 2;	// instant coupon
		$row['show_hours'] = empty($row['end_hour']) ? 0 : 1;
		$row['show_price'] = empty($row['price']) ? 0 : 1;
		
		//check the client type and version
		$detect = new Mobile_Detect();
		if ($detect->isIOS()){
			$deviceType = 'iPhone';
		} elseif ($detect->isAndroidOS()) {
			$deviceType = 'Android';
		} else {
			$deviceType = 'Web';
		}
		$row['agent_string'] = Yii::app()->request->getUserAgent();
		if (false !== strpos($row['agent_string'], 'Apache-HttpClient')) {
			$deviceType = 'Android';
		}
		$row['client_type'] = $deviceType;
		$row['published_time'] = date('Y-m-d H:i:s');
		
		//1. fetch merchants
		$sql_insert = 'INSERT INTO tbl_merchant_special
			(id_merchant, show_price, price, value, discount, show_hours, start_hour, end_hour, week_days, start_date, end_date, max_number, content, type, status, published_time, update_timestamp, client_type, agent_string)
			VALUES(:id_merchant, :show_price, :price, :value, :discount, :show_hours, :start_hour, :end_hour, :week_days, :start_date, :end_date, :max_number, :content, :type, :status, :published_time, NOW(), :client_type, :agent_string)';
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_insert);
		$command->execute($row);
		$connection->active = false;
		
		//notification for this published special
		$sql_select = 'SELECT id FROM tbl_merchant_special 
			WHERE id_merchant=:id_merchant AND published_time=:published_time AND price=:price AND value=:value 
			ORDER BY update_timestamp DESC LIMIT 1 ';
		$command = $connection->createCommand($sql_select);
		$offer_row = $command->queryRow(true, array(
			':id_merchant' => $id, ':published_time' => $row['published_time'],
			':price' => $row['price'], ':value' => $row['value'],
		));
		$connection->active = false;
		
		//push notification for this special
		if (count($offer_row) > 0) {
			$request_url = Yii::app()->createAbsoluteUrl($this->module->id . '/special/notifyOffer', array('id'=>$offer_row['id']));
			
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $request_url);
			curl_setopt($ch, CURLOPT_TIMEOUT, 1);
			curl_exec($ch);
			curl_close($ch);
			
			//BUtils::PushNotificationToDevices($offer_row['id'], true);
		}
		
		$this->_sendJSON(200, BUtils::T('special_send_success_msg'));
	}
	
	/**
	 * Push notification for a special.
	 * @param int $id special ID
	 */
	public function actionNotifyOffer($id) {
		$demo = Yii::app()->getGlobalState('demo', false);
		if ($this->module->id == 'apidev') $demo = true;
		
		//check how many offer this merchant has sent out today
		$today_start_time = date('Y-m-d 00:00:00');
		$today_end_time = date('Y-m-d 23:59:59');
		
		//apidev don't care about the night time
		BUtils::PushNotificationToDevices($id, $demo);
	}
	
	/**
	 * Redeem a special.
	 *   hid=? and key=?
	 *   code - Yamii code
	 * @param type $hid
	 * @param type $key 
	 */
	public function actionRedeem() {
		$hid = Yii::app()->request->getParam('hid', null);
		$key = Yii::app()->request->getParam('key', null);
		$id = $this->_auth($hid, $key);
		
		$code = Yii::app()->request->getParam('code', null);
		if (empty($code)) $this->_sendError('The parameter "code" is missing!' );
		
		$sql_redeem = 'SELECT r.id, r.code, r.id_user, r.id_special, r.redeemed, r.redeemed_time, r.insert_timestamp,
			UNIX_TIMESTAMP(r.redeemed_time) AS uts_redeemed
			FROM tbl_merchant_special_redeem r
			INNER JOIN tbl_merchant_special s ON r.id_special=s.id
			WHERE r.code=:code AND s.id_merchant=:id_merchant';
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_redeem);
		$row = $command->queryRow(true, array(
			'code' => $code,
			'id_merchant' => $id,
		));
		
		if (empty($row)) {
			$error = 1;
			$message = BUtils::T('special_redeem_invalid_msg');
		} else if ($row['redeemed'] == 1) {
			$error = 2;
			// 'long', 'medium' and 'short'
			$redeemed_time = Yii::app()->locale->dateFormatter->formatDateTime($row['uts_redeemed'], 'medium');
			$message = BUtils::T('special_redeem_existed_msg', array('{redeemed_time}'=>$redeemed_time));
		} else {
			$error = 0;
			$message = BUtils::T('special_redeem_valid_msg');
		}
		if ($error === 0) {
			//update status with yamii code
			$sql_redeem_update = 'UPDATE tbl_merchant_special_redeem SET redeemed=1, redeemed_time=NOW() WHERE id=:id';
			$command = $connection->createCommand($sql_redeem_update);
			$command->execute(array('id'=>$row['id']));
		} else {
			//insert redeem log table
			$sql_redeem_failed = 'INSERT INTO tbl_merchant_special_redeem_log (error, code, message) VALUES (:error, :code, :message)';
			$command = $connection->createCommand($sql_redeem_failed);
			$command->execute(array('code'=>$code, 'message'=>$message, 'error'=>$error));
		}
		$connection->active = false;
		
		$this->_sendJSON(200, $message);
	}
}